package bean;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import DAO.UsuarioDAO;
import Model.Usuario;
import Utils.Conexao;
import Utils.Uteis;

public class LoginBean {
	private String user;
	private String passwd;
	private Usuario objUsuario;
	
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	
	public void setObjUsuario(Usuario objUsuario) {
		this.objUsuario = objUsuario;
	}
	public Usuario getObjUsuario() {
		return objUsuario;
	}
	
	public String login() {
		java.sql.Connection con = Conexao.getConection();
		boolean logado = false; 		
		
		try {
			String mysqlCall = "call spc_select_usuario_por_login_senha(?, ?);";
			CallableStatement call = con.prepareCall(mysqlCall);			
			String senha_criptografada = Uteis.encripta(passwd); 
			
			call.setString(1, user);
			call.setString(2, senha_criptografada);
			ResultSet res = call.executeQuery();
			
			if(res.next()) {
				Usuario user = new Usuario();
				user.setAtivo(res.getInt("ativo"));
				user.setEmail(res.getString("email"));
				user.setLogin(res.getString("login")); 
				user.setIdUsuario(res.getInt("id_usuario")); 
				user.setNome(res.getString("nome"));
				FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("currentUser", user);				
				logado = true;
				
				call.close();
				con.close();
				return "paciente_list";
			}
			else
			{
				call.close();
				con.close();
				FacesContext facesContext = FacesContext.getCurrentInstance();
				facesContext.addMessage("alerta", new FacesMessage(FacesMessage.SEVERITY_WARN, "Alerta!", "Úsuario e senha não conferem"));
				return "index";
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			FacesContext facesContext = FacesContext.getCurrentInstance();
			facesContext.addMessage("alerta", new FacesMessage(FacesMessage.SEVERITY_WARN, "Alerta!", "Úsuario e senha não conferem"));
			e.printStackTrace();
			return "index";
		}
	}
	
	public String logout()
	{
		 HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		 HttpSession session = request.getSession();
		 session.invalidate();
		 return "index";
	}
	
}
